package bma.common.langutil.testcase;

import java.io.File;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import bma.common.langutil.core.Preconditions;
import bma.common.langutil.core.ResourceUtil;
import bma.common.langutil.io.IOUtil;
import bma.common.langutil.log.LogbackUtil;

/**
 * Spring框架的测试用例工具
 * 
 * @author 关中
 * @since 1.0
 * 
 */
public class SpringTestcaseUtil {

	public static void disableDebug() {
		LogbackUtil.setLevel("org.springframework", "INFO");
	}

	public static ApplicationContext projectContext(String[] names) {
		Preconditions.checkNotNull(names);
		ApplicationContextBuilder b = new ApplicationContextBuilder();
		for (int i = 0; i < names.length; i++) {
			b.project(names[i]);
		}
		return b.build();
	}

	public static class ApplicationContextBuilder {

		private List<String> urlList = new LinkedList<String>();

		public ApplicationContextBuilder classpath(String classpath) {
			URL url = Thread.currentThread().getContextClassLoader()
					.getResource(classpath);
			Preconditions.checkNotNull(url);
			urlList.add(url.toString());
			return this;
		}

		public ApplicationContextBuilder resource(Class<?> cls, String name) {
			URL url = ResourceUtil.getResourceFromClass(cls, name);
			Preconditions.checkNotNull(url);
			urlList.add(url.toString());
			return this;
		}

		public ApplicationContextBuilder resource(Class<?> cls, String[] names) {
			for (String name : names) {
				URL url = ResourceUtil.getResourceFromClass(cls, name);
				Preconditions.checkNotNull(url);
				urlList.add(url.toString());
			}
			return this;
		}

		public ApplicationContextBuilder project(String name) {
			File file = IOUtil.getUserDirFile(name);
			Preconditions.checkNotNull(file);
			urlList.add(file.toURI().toString());
			return this;
		}

		public FileSystemXmlApplicationContext build() {
			return new FileSystemXmlApplicationContext(
					urlList.toArray(new String[0]));
		}
	}
}
